#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
SMIS数据模拟后端服务器
提供SMISDataSimu.json中的模拟数据
"""

from flask import Flask, jsonify, request
from flask_cors import CORS
import json
import os
from datetime import datetime

app = Flask(__name__)
CORS(app)  # 允许跨域请求

# 数据文件路径
DATA_FILE = 'SMISDataSimu.json'

def load_json_data():
    """加载JSON数据文件"""
    try:
        print(f"正在尝试加载文件: {DATA_FILE}")
        print(f"文件是否存在: {os.path.exists(DATA_FILE)}")
        print(f"当前工作目录: {os.getcwd()}")
        
        with open(DATA_FILE, 'r', encoding='utf-8') as f:
            data = json.load(f)
            print(f"成功加载数据，数据类型: {type(data)}")
            if isinstance(data, dict) and 'data' in data:
                print(f"data字段类型: {type(data['data'])}")
                print(f"data字段长度: {len(data['data']) if isinstance(data['data'], list) else 'N/A'}")
            print(f"完整数据结构键: {data.keys() if isinstance(data, dict) else 'Not a dict'}")
            return data
    except FileNotFoundError:
        print(f"错误: 文件 {DATA_FILE} 未找到")
        return {"msg": "数据文件未找到", "code": "404", "data": []}
    except json.JSONDecodeError as e:
        print(f"错误: JSON解析失败 - {e}")
        return {"msg": "数据文件格式错误", "code": "500", "data": []}
    except Exception as e:
        print(f"未知错误: {e}")
        return {"msg": "加载数据时发生错误", "code": "500", "data": []}

@app.route('/')
def index():
    """根路径 - 服务器状态"""
    return jsonify({
        "service": "SMIS Data Simulation Server",
        "status": "running",
        "timestamp": datetime.now().isoformat(),
        "version": "1.0.0"
    })

@app.route('/api/smis/data', methods=['GET'])
def get_smis_data():
    """获取所有SMIS数据"""
    data = load_json_data()
    return jsonify(data)

@app.route('/api/smis/orders', methods=['GET'])
def get_orders():
    """获取工单列表"""
    data = load_json_data()
    if data.get('code') != '0':
        return jsonify(data)
    
    orders = []
    for item in data.get('data', []):
        order = {
            'orderno': item.get('orderno'),
            'planqty': item.get('planqty'),
            'productspecification': item.get('productspecification'),
            'works_count': len(item.get('works', []))
        }
        orders.append(order)
    
    return jsonify({
        "msg": "success",
        "code": "0",
        "data": orders,
        "total": len(orders)
    })

@app.route('/api/smis/order/<order_no>', methods=['GET'])
def get_order_detail(order_no):
    """获取特定工单的详细信息"""
    data = load_json_data()
    if data.get('code') != '0':
        return jsonify(data)
    
    for item in data.get('data', []):
        if item.get('orderno') == order_no:
            return jsonify({
                "msg": "success",
                "code": "0",
                "data": item
            })
    
    return jsonify({
        "msg": f"工单 {order_no} 未找到",
        "code": "404",
        "data": None
    })

@app.route('/api/smis/works', methods=['GET'])
def get_works():
    """获取所有工序信息"""
    data = load_json_data()
    if data.get('code') != '0':
        return jsonify(data)
    
    all_works = []
    for item in data.get('data', []):
        order_no = item.get('orderno')
        for work in item.get('works', []):
            work_info = work.copy()
            work_info['parent_orderno'] = order_no
            all_works.append(work_info)
    
    # 支持按状态过滤
    state_filter = request.args.get('state')
    if state_filter:
        all_works = [w for w in all_works if w.get('state') == state_filter]
    
    return jsonify({
        "msg": "success",
        "code": "0",
        "data": all_works,
        "total": len(all_works)
    })

@app.route('/api/smis/works/<work_no>', methods=['GET'])
def get_work_detail(work_no):
    """获取特定工序的详细信息"""
    data = load_json_data()
    if data.get('code') != '0':
        return jsonify(data)
    
    for item in data.get('data', []):
        for work in item.get('works', []):
            if work.get('workno') == work_no:
                work_detail = work.copy()
                work_detail['parent_orderno'] = item.get('orderno')
                work_detail['parent_productspec'] = item.get('productspecification')
                return jsonify({
                    "msg": "success",
                    "code": "0",
                    "data": work_detail
                })
    
    return jsonify({
        "msg": f"工序 {work_no} 未找到",
        "code": "404",
        "data": None
    })

@app.route('/api/smis/stats', methods=['GET'])
def get_statistics():
    """获取统计信息"""
    data = load_json_data()
    if data.get('code') != '0':
        return jsonify(data)
    
    total_orders = len(data.get('data', []))
    total_works = 0
    state_stats = {}
    total_dealtime = 0
    
    for item in data.get('data', []):
        works = item.get('works', [])
        total_works += len(works)
        
        for work in works:
            state = work.get('state', '未知')
            state_stats[state] = state_stats.get(state, 0) + 1
            total_dealtime += work.get('dealtime', 0)
    
    return jsonify({
        "msg": "success",
        "code": "0",
        "data": {
            "total_orders": total_orders,
            "total_works": total_works,
            "total_dealtime_minutes": total_dealtime,
            "total_dealtime_hours": round(total_dealtime / 60, 2),
            "state_statistics": state_stats,
            "avg_works_per_order": round(total_works / total_orders, 2) if total_orders > 0 else 0
        }
    })

@app.route('/api/smis/search', methods=['GET'])
def search_data():
    """搜索功能"""
    query = request.args.get('q', '').strip()
    if not query:
        return jsonify({
            "msg": "请提供搜索关键词",
            "code": "400",
            "data": []
        })
    
    data = load_json_data()
    if data.get('code') != '0':
        return jsonify(data)
    
    results = []
    
    for item in data.get('data', []):
        # 搜索工单
        if (query.lower() in item.get('orderno', '').lower() or 
            query.lower() in item.get('productspecification', '').lower()):
            results.append({
                'type': 'order',
                'data': item
            })
        
        # 搜索工序
        for work in item.get('works', []):
            if (query.lower() in work.get('workno', '').lower() or 
                query.lower() in work.get('workname', '').lower()):
                work_result = work.copy()
                work_result['parent_orderno'] = item.get('orderno')
                results.append({
                    'type': 'work',
                    'data': work_result
                })
    
    return jsonify({
        "msg": "success",
        "code": "0",
        "data": results,
        "total": len(results),
        "query": query
    })

@app.errorhandler(404)
def not_found(error):
    """404错误处理"""
    return jsonify({
        "msg": "接口不存在",
        "code": "404",
        "data": None
    }), 404

@app.errorhandler(500)
def internal_error(error):
    """500错误处理"""
    return jsonify({
        "msg": "服务器内部错误",
        "code": "500",
        "data": None
    }), 500

if __name__ == '__main__':
    # 检查数据文件是否存在
    if not os.path.exists(DATA_FILE):
        print(f"警告: 数据文件 {DATA_FILE} 不存在")
    
    print("=" * 50)
    print("SMIS数据模拟服务器启动中...")
    print("=" * 50)
    print("可用的API端点:")
    print("  GET  /                     - 服务器状态")
    print("  GET  /api/smis/data        - 获取所有数据")
    print("  GET  /api/smis/orders      - 获取工单列表")
    print("  GET  /api/smis/order/<id>  - 获取特定工单详情")
    print("  GET  /api/smis/works       - 获取工序列表")
    print("  GET  /api/smis/works?state=<状态> - 按状态过滤工序")
    print("  GET  /api/smis/works/<id>  - 获取特定工序详情")
    print("  GET  /api/smis/stats       - 获取统计信息")
    print("  GET  /api/smis/search?q=<关键词> - 搜索功能")
    print("=" * 50)
    print("服务器将在 http://localhost:5000 启动")
    print("按 Ctrl+C 停止服务器")
    print("=" * 50)
    
    app.run(debug=True, host='0.0.0.0', port=5000)
